package com.v2future.sjt.collegecheckingattendance.fruit.research;

import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.event.adapter.ReleaseEventImgGridAdapter;
import com.v2future.sjt.collegecheckingattendance.event.bean.ReleaseEventImageBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ConditionTypeBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ResearchTypeAddBean;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ResearchTypeBean;
import com.v2future.sjt.collegecheckingattendance.fruit.research.fragment.ArticleInputFragment;
import com.v2future.sjt.collegecheckingattendance.fruit.research.fragment.OtherInputFragment;
import com.v2future.sjt.collegecheckingattendance.fruit.research.fragment.PatentInputFragment;
import com.v2future.sjt.collegecheckingattendance.fruit.research.fragment.ProjectInputFragment;
import com.v2future.sjt.collegecheckingattendance.fruit.research.fragment.TreatiseInputFragment;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 按类型添加科研
 */
public class AddOneResearchTypeActivity extends MainActivity {

    @Bind(R.id.layout_add_content)
    FrameLayout layoutAddContent;
    @Bind(R.id.gv_release_images)
    GridView gvReleaseImages;

    ArticleInputFragment articleInputFragment;
    TreatiseInputFragment treatiseInputFragment;
    ProjectInputFragment projectInputFragment;
    PatentInputFragment patentInputFragment;
    OtherInputFragment otherInputFragment;

    /**
     * 适配器装载图片的列表
     */
    List<ReleaseEventImageBean> imageDataList;

    /**
     * 图片展示适配器
     */
    ReleaseEventImgGridAdapter adapter;

    int REQUEST_IMAGE = 1001;

    private ConditionTypeBean conditionTypeBean;
    private ResearchTypeBean researchTypeBean;

    @Override
    public void init() {
        conditionTypeBean = (ConditionTypeBean) getIntent().getSerializableExtra(IntentKey.FRUIT_TYPE);
        researchTypeBean = (ResearchTypeBean) getIntent().getSerializableExtra(IntentKey.RESEARCH_TYPE);
        imageDataList = new ArrayList<>();
        ReleaseEventImageBean bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_add_research_type);
        ButterKnife.bind(this);
        setTitleText("添加" + researchTypeBean.getResearchSubjectName());
        initTitleBack(null);
        setRightText("完成", finishListener);
    }

    @Override
    public void initAfter() {
        adapter = new ReleaseEventImgGridAdapter(this, imageDataList);
        gvReleaseImages.setAdapter(adapter);
        gvReleaseImages.setOnItemClickListener(imageClickListener);
        articleInputFragment = new ArticleInputFragment();
        treatiseInputFragment = new TreatiseInputFragment();
        projectInputFragment = new ProjectInputFragment();
        patentInputFragment = new PatentInputFragment();
        otherInputFragment = new OtherInputFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if ("1".equals(researchTypeBean.getResearchSubjectId())) {//论文
            transaction.replace(R.id.layout_add_content, articleInputFragment);
        } else if ("2".equals(researchTypeBean.getResearchSubjectId())) {//专著
            transaction.replace(R.id.layout_add_content, treatiseInputFragment);
        } else if ("3".equals(researchTypeBean.getResearchSubjectId())) {//项目
            transaction.replace(R.id.layout_add_content, projectInputFragment);
        } else if ("4".equals(researchTypeBean.getResearchSubjectId())) {//专利
            transaction.replace(R.id.layout_add_content, patentInputFragment);
        } else if ("5".equals(researchTypeBean.getResearchSubjectId())) {//其他
            transaction.replace(R.id.layout_add_content, otherInputFragment);
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 刷新图片
     */
    private void refreshImages(ArrayList<String> path) {
        imageDataList.clear();
        ReleaseEventImageBean bean = null;
        for (int i = 0; i < path.size(); i++) {
            bean = new ReleaseEventImageBean();
            bean.setImageUrl(path.get(i).toString());
            imageDataList.add(bean);
        }
        bean = new ReleaseEventImageBean();
        imageDataList.add(bean);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                // Get the result list of select image paths
                ArrayList<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path.size() > 0) {
                    imageUrls = path;//保存已选的图片路径
                    refreshImages(path);
                    showLoadingDialog();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            compressImages();
                            cancelLoadingDialog();
                        }
                    }.start();
                }
            }
        }
    }

    /**
     * 完成事件
     */
    private View.OnClickListener finishListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ("1".equals(researchTypeBean.getResearchSubjectId())) {//论文
                ResearchTypeAddBean bean = articleInputFragment.getAddBean();
                if (null != bean) {
                    doAddUserFruit(bean);
                } else {
                    tip("输入信息有误");
                }
            } else if ("2".equals(researchTypeBean.getResearchSubjectId())) {//专著
                ResearchTypeAddBean bean = treatiseInputFragment.getAddBean();
                if (null != bean) {
                    doAddUserFruit(bean);
                } else {
                    tip("输入信息有误");
                }
            } else if ("3".equals(researchTypeBean.getResearchSubjectId())) {//项目
                ResearchTypeAddBean bean = projectInputFragment.getAddBean();
                if (null != bean) {
                    doAddUserFruit(bean);
                } else {
                    tip("输入信息有误");
                }
            } else if ("4".equals(researchTypeBean.getResearchSubjectId())) {//专利
                ResearchTypeAddBean bean = patentInputFragment.getAddBean();
                if (null != bean) {
                    doAddUserFruit(bean);
                } else {
                    tip("输入信息有误");
                }
            } else if ("5".equals(researchTypeBean.getResearchSubjectId())) {//其他
                ResearchTypeAddBean bean = otherInputFragment.getAddBean();
                if (null != bean) {
                    doAddUserFruit(bean);
                } else {
                    tip("输入信息有误");
                }
            }
        }
    };

    /**
     * 添加成长
     *
     * @param bean 参数
     */
    private void doAddUserFruit(ResearchTypeAddBean bean) {
        BaseRequestParams params = new BaseRequestParams(this, formatUrlDo(Constants.PUBLISH_EVENT));
        params.setMultipart(true);
        params.addQueryStringParameter("type", "3");//3表示发布成长
        params.addQueryStringParameter("condtionTypeId", conditionTypeBean.getConditonTypeId());
        params.addQueryStringParameter("researchSubjectId", researchTypeBean.getResearchSubjectId());
        params.addQueryStringParameter("attr1", bean.getAttr1());
        params.addQueryStringParameter("attr2", bean.getAttr2());
        params.addQueryStringParameter("attr3", bean.getAttr3());
        params.addQueryStringParameter("attr4", bean.getAttr4());
        params.addQueryStringParameter("attr5", bean.getAttr5());
        params.addQueryStringParameter("attr6", bean.getAttr6());
        params.addQueryStringParameter("attr7", bean.getAttr7());
        params.addQueryStringParameter("attr8", bean.getAttr8());
        if (null != imageUrls && imageUrls.size() > 0) {
            for (int i = 0; i < imageUrls.size(); i++) {
                params.addQueryStringParameter("imageName" + i, urlEncode(imageUrls.get(i).toString()));
                params.addBodyParameter("imageBody" + i, imageFiles.get(i), null);
            }
        }
        showLoadingDialog();
        NetUtils.doPostRequestWithFiles(this, params, new NetTaskListener<BaseResponseBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                showOneBtnDialog(getString(R.string.notice), "提交科研完成", getString(R.string.iknow), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    AdapterView.OnItemClickListener imageClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            if (dataList.get(position).getImageUrl() == null) {
            Intent intent = new Intent(AddOneResearchTypeActivity.this, MultiImageSelectorActivity.class);
            // whether show camera
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
            // max select image amount
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 4);
            // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
            // default select images (support array list)
            intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imageUrls);
            startActivityForResult(intent, REQUEST_IMAGE);
//            }
        }
    };
}
